/**
 * 将列表转换为树形结构
 * @param {*} data 列表数据
 * @param {*} parentKey 父级键
 * @param {*} childrenKey 子级键
 * @returns 
 */
const listToTree = (data, parentKey, childrenKey) => {
  const parents = data.filter(category => !category[parentKey])
  const children = data.filter(category => category[parentKey])

  function format(parentList, childrenList, parentId, id) {
    parentList.forEach(parent => {
      childrenList.forEach((child) => {
        if (child[parentId] === parent[id]) {
          format([child], childrenList, parentId, id)

          if(parent.children) {
            parent.children.push(child)
          } else {
            parent.children = [child]
          }
        }
      })
    })
  }
  format(parents, children, parentKey, childrenKey)

  return parents
}

module.exports = {
  listToTree
}